package com.kele.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kele.common.model.response.PageResult;
import com.kele.common.model.response.ResultObject;
import com.kele.model.order.Order;
import com.kele.model.order.OrderItem;
import com.kele.order.mapper.OrderItemMapper;
import com.kele.order.mapper.OrderMapper;
import com.kele.order.model.Cart;
import com.kele.utils.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderService {


    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional
    public ResultObject<Map<String,String>> order(String userId, List<OrderItem> orderItemList){
        IdWorker idWorker = new IdWorker();
        long orderId = idWorker.nextId();

        /*Map map = new HashMap<>();
        map.put("userId",userId);
        map.put("orderItemList",orderItemList);
        map.put("orderId",orderId);
        rabbitTemplate.convertAndSend("exchange_direct_order","order",map);
        */
        //

        StringBuilder goodsDesc = new StringBuilder();
        BigDecimal payment = new BigDecimal("0");
        for (OrderItem orderItem : orderItemList) {
            payment = payment.add(orderItem.getTotalFee());
        }
        Order order = new Order();
        order.setOrderId(orderId);
        order.setUserId(userId);
        order.setPayment(payment);
        order.setCreateTime(new Date());
        order.setStatus("1");
        orderMapper.insert(order);
        //Long orderId = order.getOrderId();

        orderItemList.forEach(orderItem->{
            orderItem.setOrderId(orderId);
            orderItemMapper.insert(orderItem);
            goodsDesc.append(orderItem.getTitle());
        });
        //以下两行代码保证消息可靠
        /*
        listener:
          simple:
            acknowledge-mode: manual
         */
        clearCart(userId,orderItemList);
        //发放优惠券，积分
        Map<String,String> map = new HashMap();
        map.put("orderId",String.valueOf(orderId));
        map.put("payment",payment.multiply(new BigDecimal("100"))
                .toBigInteger().toString());
        map.put("goodsDesc",goodsDesc.toString());
        return new ResultObject<>(true,"1","",map);
    }

    public PageResult<Order> findPage(String userId,Integer pageNo, Integer pageSize, Map searchMap) {
        Page<Order> page = new Page<>(pageNo,pageSize);

        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Order::getUserId,userId);//userId该用户

        String status = (String)searchMap.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.lambda().like(Order::getStatus,status);
        }

        String minPrice = (String)searchMap.get("minPrice");
        String maxPrice = (String)searchMap.get("maxPrice");
        Double price_min = 0D;
        Double price_max = 99999999D;
        if(!StringUtils.isEmpty(minPrice)){
            try {
                price_min = Double.parseDouble(minPrice);
                queryWrapper.lambda().gt(Order::getPayment,price_min);
            }catch (NumberFormatException e){}
        }
        if(!StringUtils.isEmpty(maxPrice)){
            try {
                price_max = Double.parseDouble(maxPrice);
                queryWrapper.lambda().le(Order::getPayment,price_max);
            }catch (NumberFormatException e){}
        }

        queryWrapper.lambda().orderByDesc(Order::getCreateTime);

        Page<Order> page1 = orderMapper.selectPage(page, queryWrapper);

        return new PageResult<>(page1.getTotal(),page1.getRecords());

    }

    @Autowired
    CartService cartService;

    /**
     * 清除购物车
     * @param userId
     * @param orderItemList
     */
    private void clearCart(String userId,List<OrderItem> orderItemList){
        Cart cart_old = cartService.getCart(userId);

        Iterator<OrderItem> iterator = cart_old.iterator();
        while (iterator.hasNext()){
            OrderItem orderItem = iterator.next();
            for (OrderItem buyItem : orderItemList) {
                if(orderItem.getGoodsId().equals(buyItem.getGoodsId())){
                    iterator.remove();
                }
            }
        }

        cartService.resetCart(userId,cart_old);
    }

}
